import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Piece } from '@/types/piece'
import { savePieceComponentPack } from '@/apis/piece'
import { Input } from '@/components/ui/input'
import { toast } from 'sonner'

interface ShareFormProps {
  pieces: (Piece | undefined)[]
  onShareSuccess?: () => void
}

const ShareForm: React.FC<ShareFormProps> = ({ pieces, onShareSuccess }) => {
  const [open, setOpen] = useState(false)
  const [shareName, setShareName] = useState('')
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()

  // 生成分享文本，保留原详细文本，最后追加同类碎片的简要汇总（全体pieces，按alias计数）
  const getShareText = () => {
    // 汇总函数，按 alias 和 P数 计数
    function summarizeByAliasAndScore(pieces: (Piece | undefined)[]) {
      // map: key -> { alias, score, count }
      const map = new Map<
        string,
        { alias: string; score: number; count: number }
      >()
      for (const p of pieces) {
        if (!p) continue
        const alias = p.alias
        const score = p.score ?? 0
        const key = `${alias}||${score}`
        if (map.has(key)) {
          map.get(key)!.count++
        } else {
          map.set(key, { alias, score, count: 1 })
        }
      }
      // 排序：alias字母序，同alias下P数降序
      return Array.from(map.values())
        .sort((a, b) => a.alias.localeCompare(b.alias) || b.score - a.score)
        .map(
          (item, idx) =>
            `${idx + 1}. ${item.alias} (${item.score}P) * ${item.count}`
        )
    }

    // 原始详细文本
    function detailList(pieces: (Piece | undefined)[], label: string) {
      return [
        label,
        ...pieces
          .filter(Boolean)
          .map((piece, idx) => {
            if (!piece) return ''
            return `${idx + 1}. ${piece.name}（${piece.alias}）${
              piece.score ?? 0
            }P 效果:${piece.describe ?? ''}`
          })
          .filter(Boolean)
      ].join('\n')
    }

    const equip = pieces.slice(0, 45)
    const jewelry = pieces.slice(45)
    const equipDetail = detailList(equip, '装备碎片')
    const jewelryDetail = detailList(jewelry, '首饰碎片')
    const allSummary = ['碎片汇总', ...summarizeByAliasAndScore(pieces)].join(
      '\n'
    )
    return [equipDetail, jewelryDetail, '', allSummary]
      .filter(Boolean)
      .join('\n\n')
  }

  // 分享保存处理
  const handleShare = async () => {
    if (!shareName.trim()) {
      toast.warning('请输入分享名称')
      return
    }
    setLoading(true)
    const content = pieces.map((p) => p?.id ?? '').join(',')
    const data = {
      id: 0,
      name: shareName,
      title: shareName,
      avatar: '',
      score: 0,
      content,
      status: 1,
      created_at: '',
      created_by: 0,
      updated_at: '',
      updated_by: 0
    }
    try {
      const result = await savePieceComponentPack(data)
      setOpen(false)
      toast.success('分享成功！')
      onShareSuccess?.()
      if (result?.id) navigate(`/pieces/${result.id}`)
    } catch {
      toast.error('分享失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          size="sm"
          variant="outline"
          className="rounded-md border-primary/40 bg-gradient-to-r from-white/80 to-slate-100/80 px-4 py-1 font-semibold text-primary shadow-sm transition-all duration-200 hover:scale-105 hover:shadow-lg dark:from-neutral-900/80 dark:to-neutral-800/80 dark:text-neutral-100"
        >
          分享
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="mb-2 flex items-center gap-2 text-lg font-bold text-primary dark:text-neutral-100">
            共享我的碎片方案
          </DialogTitle>
        </DialogHeader>
        <div className="flex flex-col gap-3">
          <Input
            placeholder="请输入分享名称（必填）"
            value={shareName}
            onChange={(e) => setShareName(e.target.value)}
            maxLength={32}
            className="rounded border border-slate-300 bg-white/90 px-3 py-2 text-base shadow-sm focus:border-primary focus:ring-2 focus:ring-primary/20 dark:border-neutral-700 dark:bg-neutral-900/80"
            autoFocus
          />
          <textarea
            className="min-h-[180px] w-full rounded border border-slate-200 bg-slate-50 p-2 text-sm text-slate-700 shadow-inner focus:border-primary focus:ring-2 focus:ring-primary/20 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100"
            value={getShareText()}
            readOnly
          />
          <Button
            className="mt-1 w-full rounded-md py-2 text-base font-semibold transition-all duration-200"
            onClick={handleShare}
            disabled={loading || !shareName.trim()}
          >
            {loading ? '保存中…' : '保存分享'}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}

export default ShareForm
